package org.jeecg.modules.device.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.codec.Base64;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.DeviceConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.encryption.AesEncryptUtil;
import org.jeecg.modules.device.entity.DevDeviceInfo;
import org.jeecg.modules.device.entity.DevDeviceRecord;
import org.jeecg.modules.device.entity.DeviceLog;
import org.jeecg.modules.device.service.IDevDeviceInfoService;
import org.jeecg.modules.device.service.IDeviceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @Description: 设备信息表
 * @Author: jeecg-boot
 * @Date:   2024-04-17
 * @Version: V1.0
 */
@Api(tags="设备信息表")
@RestController
@RequestMapping("/device/devDeviceInfo")
@Slf4j
public class DevDeviceInfoController extends JeecgController<DevDeviceInfo, IDevDeviceInfoService> {
	@Autowired
	private IDevDeviceInfoService devDeviceInfoService;
	@Autowired
	private IDeviceLogService deviceLogService;
	
	/**
	 * 分页列表查询
	 *
	 * @param devDeviceInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "设备信息表-分页列表查询")
	@ApiOperation(value="设备信息表-分页列表查询", notes="设备信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DevDeviceInfo>> queryPageList(DevDeviceInfo devDeviceInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<DevDeviceInfo> queryWrapper = QueryGenerator.initQueryWrapper(devDeviceInfo, req.getParameterMap());
		Page<DevDeviceInfo> page = new Page<DevDeviceInfo>(pageNo, pageSize);
		IPage<DevDeviceInfo> pageList = devDeviceInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param devDeviceInfo
	 * @return
	 */
	@AutoLog(value = "设备信息表-添加")
	@ApiOperation(value="设备信息表-添加", notes="设备信息表-添加")
	@RequiresPermissions("device:iot_dev_device_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DevDeviceInfo devDeviceInfo) {
		if(StringUtils.isEmpty(devDeviceInfo.getDeviceId())){
			// 编号作为设备序列号 - 设备身份ID 需要手动
			throw new JeecgBootException("设备序列号不能为空");
		}
		if(StringUtils.isEmpty(devDeviceInfo.getDeviceCode())){
			// 编号作为设备序列号 - 设备身份ID 需要手动
			devDeviceInfo.setDeviceCode(devDeviceInfo.getDeviceId());
		}
		devDeviceInfoService.save(devDeviceInfo);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param devDeviceInfo
	 * @return
	 */
	@AutoLog(value = "设备信息表-编辑")
	@ApiOperation(value="设备信息表-编辑", notes="设备信息表-编辑")
	@RequiresPermissions("device:iot_dev_device_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DevDeviceInfo devDeviceInfo) {
		if(StringUtils.isEmpty(devDeviceInfo.getDeviceId())){
			throw new JeecgBootException("设备序列号不能为空");
		}
		if(StringUtils.isEmpty(devDeviceInfo.getDeviceCode())){
			// 编号作为设备序列号 - 设备身份ID 需要手动
			devDeviceInfo.setDeviceCode(devDeviceInfo.getDeviceId());
		}
		devDeviceInfoService.updateById(devDeviceInfo);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备信息表-通过id删除")
	@ApiOperation(value="设备信息表-通过id删除", notes="设备信息表-通过id删除")
	@RequiresPermissions("device:iot_dev_device_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		devDeviceInfoService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "设备信息表-批量删除")
	@ApiOperation(value="设备信息表-批量删除", notes="设备信息表-批量删除")
	@RequiresPermissions("device:iot_dev_device_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.devDeviceInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "设备信息表-通过id查询")
	@ApiOperation(value="设备信息表-通过id查询", notes="设备信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DevDeviceInfo> queryById(@RequestParam(name="id",required=true) String id) {
		DevDeviceInfo devDeviceInfo = devDeviceInfoService.getById(id);
		if(devDeviceInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(devDeviceInfo);
	}


    /**
    * 导出excel
    *
    * @param request
    * @param devDeviceInfo
    */
    @RequiresPermissions("device:iot_dev_device_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DevDeviceInfo devDeviceInfo) {
        return super.exportXls(request, devDeviceInfo, DevDeviceInfo.class, "设备信息表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("device:iot_dev_device_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DevDeviceInfo.class);
    }

	 /**
	  *   开阀
	  *
	  * @param devDeviceInfo
	  * @return
	  */
	 @AutoLog(value = "设备信息表-开阀")
	 @ApiOperation(value="设备信息表-开阀", notes="设备信息表-开阀")
	 @PostMapping(value = "/openCmd")
	 public Result<String> openCmd(@RequestBody DevDeviceInfo devDeviceInfo) {
		 if(null == devDeviceInfo.getId()){
			 throw new JeecgBootException("设备不能为空");
		 }
		 DevDeviceInfo info = devDeviceInfoService.getById(devDeviceInfo.getId());
		 if(info==null) {
			 return Result.error("未找到对应数据");
		 }
		 if("5".equals(info.getDeviceType())){// 监控
			 return Result.error("设备不支持");
		 }
		 //下发指令
		 devDeviceInfo.setCommandType("open");
		 JSONObject rsObj = devDeviceInfoService.deviceCommand(devDeviceInfo);
		 if(0 == rsObj.getInteger("code")){
			 System.out.println(rsObj.toJSONString());
		 }else {
			 return  Result.error(rsObj.getString("msg"));
		 }
		 return Result.OK("下发指令成功！");
	 }

	 /**
	  *   关阀
	  *
	  * @param devDeviceInfo
	  * @return
	  */
	 @AutoLog(value = "设备信息表-关阀")
	 @ApiOperation(value="设备信息表-关阀", notes="设备信息表-关阀")
	 @PostMapping(value = "/closeCmd")
	 public Result<String> closeCmd(@RequestBody DevDeviceInfo devDeviceInfo) {
		 if(null == devDeviceInfo.getId()){
			 throw new JeecgBootException("设备不能为空");
		 }
		 DevDeviceInfo info = devDeviceInfoService.getById(devDeviceInfo.getId());
		 if(info==null) {
			 return Result.error("未找到对应数据");
		 }
		 if("5".equals(info.getDeviceType())){// 监控
			 return Result.error("设备不支持");
		 }
		 //下发指令
		 devDeviceInfo.setCommandType("close");
		 JSONObject rsObj = devDeviceInfoService.deviceCommand(devDeviceInfo);
		 if(0 == rsObj.getInteger("code")){
			 System.out.println(rsObj.toJSONString());
		 }else {
			 return  Result.error(rsObj.getString("msg"));
		 }
		 return Result.OK("下发指令成功！");
	 }

	 /**
	  * 设备上线通知
	  * messageType 消息类型=   设备数据变化 dataReport
	  * 				设备命令响应 commandResponse
	  * 				设备事件上报eventReport
	  * 				设备上下线 deviceOnlineOfflineReport
	  * 				TUP合并数据变化dataReportTupUnion
	  * 				设备增加删除addDeleteDevice
	  *
	  */
	 @PostMapping(value = "/api/deviceNotify")
	 public void deviceNotify(@RequestBody JSONObject request){
		 String messageType = request.getString("messageType");
		 String deviceId = request.getString("deviceId"); // 设备ID
		 DevDeviceInfo deviceInfo = devDeviceInfoService.queryByDeviceId(deviceId);
		 if(null == deviceInfo){
			 return;
		 }
		 if("dataReport".equals(messageType)){
			 // 设备数据变化
			 // String deviceType = request.getString("deviceType"); // 设备标识（保留字段）
			 // String timestamp = DateUtils.formatDate(request.getLong("timestamp")); //时间
			 // String protocol = request.getString("protocol"); // 设备ID
			 JSONObject payloadJson = request.getJSONObject("payload");// 设备标识（保留字段）

			 System.out.println(request.getString("deviceId")+" 于"+
					 DateUtils.formatDate("yyyy-MM-dd hh:mm:ss") +"设备数据变化："+
					 request.getJSONObject("payload").toJSONString());

			 DeviceLog deviceLog = new DeviceLog();
			 deviceLog.setDevId(null != deviceInfo ? deviceInfo.getId().toString() : null); // 系统设备ID
			 deviceLog.setDeviceId(deviceId); //第三方平台设备ID
			 deviceLog.setTimestamp(DateUtils.getTimestamp(request.getLong("timestamp")));
			 deviceLog.setMessageType("dataReport");
			 deviceLog.setContent(payloadJson.toJSONString());
			 deviceLogService.save(deviceLog);

			 // 增加设备实时读数
			 String apPdata = payloadJson.getString("APPdata");
			 byte[] apPdataByte = Base64.decode(apPdata);
			 String apPdataHex = AesEncryptUtil.bytesToHex(apPdataByte);

			 devDeviceInfoService.saveDeviceReadData(deviceInfo.getDeviceId(), deviceInfo.getDeviceType(),
					 deviceInfo.getDeviceUnit(), apPdataHex);
		 }else if("commandResponse".equals(messageType)){
			 // 设备命令响应
			 System.out.println(request.getString("deviceId")+" 于"+
					 DateUtils.formatDate("yyyy-MM-dd hh:mm:ss") +"命令响应结果："+
					 request.getJSONObject("result").toJSONString());

			 DeviceLog deviceLog = new DeviceLog();
			 deviceLog.setDevId(null != deviceInfo ? deviceInfo.getId().toString() : null); // 系统设备ID
			 deviceLog.setDeviceId(deviceId); //第三方平台设备ID
			 deviceLog.setTimestamp(DateUtils.getTimestamp(request.getLong("timestamp")));
			 deviceLog.setMessageType("commandResponse");
			 deviceLog.setContent(request.getJSONObject("result").toJSONString());
			 deviceLogService.save(deviceLog);
		 }else if("deviceOnlineOfflineReport".equals(messageType)){
			 // 设备上下线
			 System.out.println(request.getString("deviceId")+" 于"+
					 DateUtils.formatDate(request.getLong("timestamp")) +
					 (1 == request.getInteger("eventType") ? "上线": "下线"));

			 DeviceLog deviceLog = new DeviceLog();
			 deviceLog.setDevId(null != deviceInfo ? deviceInfo.getId().toString() : null); // 系统设备ID
			 deviceLog.setDeviceId(deviceId); //第三方平台设备ID
			 deviceLog.setTimestamp(DateUtils.getTimestamp(request.getLong("timestamp")));
			 deviceLog.setMessageType("deviceOnlineOfflineReport");
			 deviceLog.setContent(request.getInteger("eventType") == 1 ? "上线" : "下线");
			 deviceLogService.save(deviceLog);
		 }
		 System.out.println(request);
	 }
}
